package org.jeecg.modules.upload;

import org.jeecg.common.util.DateUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * 上传文件类
 *
 * @author liujiamiao
 * @email 2544296058@qq.com
 * @date 2020-11-04 10:48
 */

public class FileUploadUtils {

    /**
     * 上传文件，并返回地址
     * @param uploadFile
     * @param filePath 只支持images、excels、words、files
     * @return
     */
    public static String upload(MultipartFile uploadFile,String filePath) throws IOException {

        //获取文件名
        String filename = uploadFile.getOriginalFilename();
        //找到最后的.
        int index = filename.lastIndexOf(".");

        String uuid = UUID.randomUUID().toString().replace("-", "");
        //uuid+后缀名
        filename = uuid+filename.substring(index);

        String date = DateUtils.formatDate(new Date(), "yyyy-MM-dd");

        String path = "D:\\upFiles\\"+filePath+"\\"+date+"\\";
        File file = new File(path);
        if (!file.exists()) {
            file.mkdir();
        }

        uploadFile.transferTo(new File(path,filename));
//        InputStream is = uploadImage.getInputStream();
//        FileOutputStream fos = new FileOutputStream(new File(path,filename));
//        int len = -1;
//        byte[] b = new byte[1024];
//        while((len = is.read(b)) !=-1){
//            fos.write(b,0,len);
//        }
//        fos.close();



        //返回图片相对地址，而整个项目的地址由request获取
        return filePath+"\\"+date+"\\"+filename;
    }


}
